package com.hl.apilibrary;

import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import okhttp3.ResponseBody;

public class DownLoadRunnable implements Runnable {
    private ResponseBody body;
    private OnDownLoadCallback callback;
    private String filePath;

    public DownLoadRunnable(ResponseBody body, String filePath, OnDownLoadCallback callback) {
        this.body = body;
        this.filePath = filePath;
        this.callback = callback;
    }

    @Override
    public void run() {
        if (body == null || TextUtils.isEmpty(filePath)) {
            if (callback != null)
                callback.onError("");
        } else {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            } else {
                try {
                    Objects.requireNonNull(file.getParentFile()).createNewFile();
                } catch (IOException e) {
                    if (callback != null)
                        callback.onError("" + e.getMessage());
                }
            }

            InputStream inputStream = null;
            byte[] buffer = new byte[8192];
            FileOutputStream fileOutputStream = null;
            long progress = 0;
            try {
                inputStream = body.byteStream();
                int len;
                fileOutputStream = new FileOutputStream(filePath);
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                    progress += len;
                    if (callback == null)
                        continue;
                    callback.onProgress(progress, body.contentLength());

                }
                fileOutputStream.flush();
                if (callback != null)
                    callback.onFinish(file.getPath());
            } catch (IOException e) {
                if (callback != null)
                    callback.onError("" + e.getMessage());
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();

                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
